package qingyu.ai.ui.personal;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.vondear.rxtools.view.RxToast;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import qingyu.ai.R;
import qingyu.ai.base.BaseActivity2;
import qingyu.ai.common.Constants;
import qingyu.ai.common.net.APIFactory;
import qingyu.ai.common.net.NetRequestAdapter;
import qingyu.ai.common.net.NetworkRequestCalback;
import qingyu.ai.common.net.RetrofitHttpUtil;
import qingyu.ai.common.util.CliperListener;
import qingyu.ai.common.util.CliperManager;
import qingyu.ai.common.util.FuncUtil;
import qingyu.ai.common.util.SPUtil;
import qingyu.ai.domain.UserInfoData;
import qingyu.ai.ui.safe.bind.BindAccountActivity;
import qingyu.ai.ui.safe.login.LoginActivity;
import qingyu.ai.ui.safe.password.ChangePasswordActivity;

import static qingyu.ai.common.util.CliperManager.REQUEST_CAPTURE;
import static qingyu.ai.common.util.CliperManager.REQUEST_CROP_PHOTO;
import static qingyu.ai.common.util.CliperManager.REQUEST_PICK;
import static qingyu.ai.common.util.FileUtil.getRealFilePathFromUri;

public class PersonalActivity extends BaseActivity2 implements NetworkRequestCalback, View.OnClickListener {

    @BindView(R.id.person_image)
    SimpleDraweeView personImage;
    @BindView(R.id.person_name)
    EditText personName;
    @BindView(R.id.person_mobile)
    TextView personMobile;
    @BindView(R.id.bind)
    RelativeLayout bind;
    @BindView(R.id.smart_push)
    RelativeLayout smartPush;
    @BindView(R.id.logout)
    RelativeLayout logout;
    @BindView(R.id.update_pass)
    RelativeLayout updatePass;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal);
        ButterKnife.bind(this);
        initView();
    }


    @Override
    protected void onResume() {
        super.onResume();
        personImage.setOnClickListener(this);
        String account = SPUtil.getString(Constants.userinfo.account, "");
        String nick_name = SPUtil.getString(Constants.userinfo.nickname, "");
        if (!TextUtils.isEmpty(account)) {
            personMobile.setText(account);
        }
        if (!TextUtils.isEmpty(nick_name)) {
            personName.setText(nick_name);
        }
    }

    private void initView() {
        ButterKnife.bind(this);
        initToolBar(getString(R.string.title_activity_personal), R.mipmap.navbar_icon_back);
        personName.setText(SPUtil.getString(Constants.userinfo.nickname, ""));
        hidePartAccount();
        updateIcon();
    }

    private void hidePartAccount() {
        String phoneNum = SPUtil.getString(Constants.userinfo.account, "");
        String replacePhoneNumber = FuncUtil.replacePhoneNumber(phoneNum);
        personMobile.setText(replacePhoneNumber);
    }

    private void updateIcon() {
        String iconUrl = SPUtil.getString(Constants.userinfo.iconUrl, null);
        if (!TextUtils.isEmpty(iconUrl))
            personImage.setImageURI(Uri.parse(iconUrl));
        else
            personImage.setImageResource(R.mipmap.headportrait);
    }

    @Override
    public void back() {
        updateUserInfo();
    }

    private void updateUserInfo() {
        String new_nick_name = personName.getText().toString();
        String old_nick_name = SPUtil.getString(Constants.userinfo.nickname, "");
        String token = SPUtil.getString(Constants.userinfo.access_token, "");
        if (TextUtils.isEmpty(new_nick_name)) {
            RxToast.error("用户昵称不能为空！");
            return;
        }
        if (!new_nick_name.equals(old_nick_name)) {
            Map<String, String> map = new HashMap<>();
            map.put("nickname", new_nick_name);
            map.put("token", token);
            new APIFactory(this, RetrofitHttpUtil.BASE_URL)
                    .updateUserInfo(map, new NetRequestAdapter<UserInfoData>(new NetworkRequestCalback<UserInfoData>() {
                        @Override
                        public void onSuccess(UserInfoData data) {
                            String nickname = data.getMember().getNickname();
                            String iconUrl = data.getMember().getAvatar();
                            SPUtil.putString(Constants.userinfo.nickname, nickname);
                            SPUtil.putString(Constants.userinfo.iconUrl, iconUrl);
                            PersonalActivity.this.finish();
                            RxToast.success("用户资料修改成功");
                        }

                        @Override
                        public void onError(int errorCode, String erorMsg) {
                            PersonalActivity.this.finish();
                            RxToast.error(erorMsg + "-----" + errorCode);
                        }

                        @Override
                        public void onNetStart() {
                        }

                        @Override
                        public void onNetFinish() {

                        }
                    }));
        } else {
            PersonalActivity.this.finish();
        }
    }

    @Override
    public void onBackPressed() {
        updateUserInfo();
    }

    /**
     * 退出登录
     */
    @OnClick(R.id.logout)
    public void logout() {
        new AlertDialog.Builder(this)
                .setTitle("退出登陆")
                .setMessage("您确定要退出登陆吗？")
                .setIcon(R.mipmap.logo)
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        Map<String, String> token = new HashMap<>();
                        token.put("token", SPUtil.getString(Constants.userinfo.access_token, Constants.net.DEFAULT_REFRESH_TOKEN));
                        new APIFactory(PersonalActivity.this,RetrofitHttpUtil.BASE_URL)
                                .logout(token, new NetRequestAdapter<UserInfoData>(PersonalActivity.this));
                    }
                }).setNegativeButton("取消", null)
                .show();
    }

    /**
     * 修改密码
     */
    @OnClick(R.id.update_pass)
    public void updatePass() {
        startActivity(new Intent(this, ChangePasswordActivity.class));
    }

    /**
     * 第三方登陆，绑定账号
     */
    @OnClick(R.id.bind)
    public void bindAccount() {
        String account = SPUtil.getString(Constants.userinfo.account, "");
        if (TextUtils.isEmpty(account))
            startActivity(new Intent(this, BindAccountActivity.class));
    }

    @Override
    public void onSuccess(Object data) {
        RxToast.success("注销成功");
        SPUtil.remove(Constants.userinfo.nickname);
        SPUtil.remove(Constants.userinfo.iconUrl);
        SPUtil.remove(Constants.userinfo.access_token);
        SPUtil.remove(Constants.userinfo.refresh_token);
        startActivity(new Intent(PersonalActivity.this, LoginActivity.class));
        finish();
    }

    @Override
    public void onError(int errorCode, String erorMsg) {
        Log.e("xixi", errorCode + "--" + erorMsg);
        RxToast.success("登陆失效，请重新登陆");
        SPUtil.remove(Constants.userinfo.nickname);
        SPUtil.remove(Constants.userinfo.iconUrl);
        SPUtil.remove(Constants.userinfo.access_token);
        SPUtil.remove(Constants.userinfo.refresh_token);
        startActivity(new Intent(this, LoginActivity.class));
        finish();
    }

    @Override
    public void onNetStart() {

    }

    @Override
    public void onNetFinish() {

    }

    //调用照相机返回图片文件
    private File tempFile;

    @Override
    public void onClick(View v) {
        CliperManager.uploadHeadImage(this, new CliperListener() {
            @Override
            public void onResponse(File file) {
                tempFile = file;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case REQUEST_CAPTURE: //调用系统相机返回
                if (resultCode == RESULT_OK) {
                    CliperManager.gotoClipActivity(this, Uri.fromFile(tempFile));
                }
                break;
            case REQUEST_PICK:  //调用系统相册返回
                if (resultCode == RESULT_OK) {
                    Uri uri = intent.getData();
                    CliperManager.gotoClipActivity(this, uri);
                }
                break;
            case REQUEST_CROP_PHOTO:  //剪切图片返回
                if (resultCode == RESULT_OK) {
                    final Uri uri = intent.getData();
                    if (uri == null) {
                        return;
                    }

                    String cropImagePath = getRealFilePathFromUri(getApplicationContext(), uri);
                    Bitmap bitMap = BitmapFactory.decodeFile(cropImagePath);
                    personImage.setImageURI(uri);
                    //此处后面可以将bitMap转为二进制上传后台网络
                    //......

                }
                break;
        }
    }
}
